﻿using System.Collections.Generic;
using Didaku.QEngine.Common.Interfaces.Engine;
using Didaku.QEngine.Common.Wrapper.Engine;

namespace Didaku.QEngine.Methods.ChangeLogic
{
    /// <summary>合岗:取得指定柜台(源柜台)的逻辑，并合并到当前(目标)柜台中
    /// </summary>
    internal class CombineTargetCounter : IChangeLogicFunc<Pair<string, string>>
    {
        #region Implementation of IChangeLogicFunc<Pair<string,string>>

        /// <summary>逻辑调整时的条件参数:当前(目标)柜台(First),指定柜台(源柜台)(Second).
        /// </summary>
        public Pair<string, string> Condition { get; set; }

        /// <summary>执行逻辑调整的动作
        /// 合并的思路。
        /// 1.新建柜台的服务逻辑；
        /// 2.循环按逻辑库的源创建组的Clone体，并从Clone体中将队列先清除
        /// 3.再先将逻辑库的源中的(当前柜台)的队列添加进来；
        /// 4.再先将逻辑库的源中的(指定柜台)的队列添加进来；
        /// 之所以略复杂一些，是不能破坏原来的（逻辑-组-队列）引用关系；
        /// </summary>
        /// <param name="sourceLogicMap">供参考的逻辑库的源</param>
        /// <param name="currLogicMap">需调整的逻辑库</param>
        /// <returns></returns>
        public bool Execute(IDictionary<string, ServiceLogic> sourceLogicMap, IDictionary<string, ServiceLogic> currLogicMap)
        {
            var currCounterId = Condition.First; //当前(目标)柜台
            var srcCounterId = Condition.Second; //指定柜台(源柜台)

            ServiceLogic currLogicBySrcMap = sourceLogicMap[currCounterId];
            ServiceLogic srcLogicBySrcMap = sourceLogicMap[srcCounterId];

            // 1.新建柜台的服务逻辑；
            var logic = new ServiceLogic {Counter = currLogicBySrcMap.Counter};

            //看哪个组的队列多一些，按这个组的数量进行循环
            int length = (currLogicBySrcMap.Count > srcLogicBySrcMap.Count) ? currLogicBySrcMap.Count : srcLogicBySrcMap.Count;
            for (int i = 0; i < length; i++)
            {
                var group = (ServiceQueueGroup) currLogicBySrcMap[1].Clone();
                group.Clear(); // 2.循环按逻辑库的源创建组的Clone体，并从Clone体中将队列先清除
                if (currLogicBySrcMap.Count > i)
                    group.AddRange(currLogicBySrcMap[i]); //3.再先将逻辑库的源中的当前柜台的队列添加进来；
                if (srcLogicBySrcMap.Count > i)
                {
                    foreach (ServiceQueue sg in srcLogicBySrcMap[i])
                    {
                        if (group.Contains(sg))
                            continue;
                        group.Add(sg); //4.再先将逻辑库的源中的指定柜台的队列添加进来；
                    }
                }
                logic.Add(group);
            }
            currLogicMap.Remove(currCounterId);
            currLogicMap.Add(currCounterId, logic);

            return true;
        }

        #endregion
    }
}